package com.raise.drive.commons.web.springmvc.view;

import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.util.Map;

/**
 * @author Eugene Rozov
 */
public abstract class AbstractFileView implements View {

    public static final String BYTES_KEY = "fileBytes";

    private boolean isCacheable;

    public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        byte[] bytes = (byte[]) model.get(BYTES_KEY);

        if (!isCacheable) {
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0L);
        }
        response.setContentType(getContentType());
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        out.close();
    }

    public boolean isCacheable() {
        return isCacheable;
    }

    public void setCacheable(boolean cacheable) {
        isCacheable = cacheable;
    }

}
